package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取openid的url请求地址
     */
    private final String getOpenidUrl = "\n" +
            "https://api.weixin.qq.com/sns/jscode2session?"+
            "appid=APPID&secret=SECRET"+
            "&js_code=JSCODE"+
            "&grant_type=authorization_code";

    /**
     * 获取微信绑定手机号url请求地址
     */
    private final String getPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber"+
            "?access_token=ACCESS_TOKEN";

    private final String getAccessTokenUrl="https://api.weixin.qq.com/cgi-bin/token"+
            "?grant_type=client_credential"+
            "&appid=APPID"+
            "&secret=SECRET";

    /**
     * 获取openid
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        try {
            //发送HTTP GET请求
            String url = getOpenidUrl.replace("JSCODE", code).replace("APPID", appid).replace("SECRET", appSecret);
            log.info("获取openid请求地址：{}", url);
            String result = HttpUtil.get(url);
            log.info("获取openid结果：{}", result);
            JSONObject jsonObject = JSON.parseObject(result);
            return jsonObject.getString("openid");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取微信oppenid失败，请稍后重试");
        }
    }

    @Override
    public String getPhone(String detailCode) {
        try {
            CharSequence accessToken = getAccessToken();
            String url = getPhoneUrl.replace("ACCESS_TOKEN", accessToken);
            Map<String, String> paramMap = new HashMap();
            paramMap.put("code", detailCode);
            String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
            log.info("获取手机号结果：{}", result);
            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            if (phoneInfo != null){
                return phoneInfo.getString("purePhoneNumber");
            }
            throw new ServiceException("获取手机号失败，请稍后重试");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取手机号失败，请稍后重试");
        }

    }

    private CharSequence getAccessToken(){
    	String url = getAccessTokenUrl.replace("APPID", appid).replace("SECRET", appSecret);
        String result = HttpUtil.get(url);
        log.info("获取access_token结果：{}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject.getString("access_token");
    }
}
